package com.ops.uitl.tapestry;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AppCompress implements Filter {
	
	private static final String HAS_RUN_KEY = AppCompress.class.getName() + ".HAS_RUN";
	private FilterConfig config;
	
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    /**
     * do filter
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean compress = false;
        if (request.getAttribute(HAS_RUN_KEY) == null && request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            Enumeration headers = httpRequest.getHeaders("Accept-Encoding");
            while (headers.hasMoreElements()) {
                String value = (String) headers.nextElement();
                if (value.indexOf("gzip") != -1) {
                    compress = true;
                }
            }
        }
        request.setAttribute(HAS_RUN_KEY, "true");
        if (compress) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.addHeader("Content-Encoding", "gzip");
            CompressResponse compressionResponse= new CompressResponse(httpResponse);
            chain.doFilter(request, compressionResponse);
            compressionResponse.flushBuffer();
            compressionResponse.finish();
        } else {
            chain.doFilter(request, response);
        }
    }


    /**
     * destory
     */
    public void destroy() {
        config = null;
    }
    
}
